package com.anolesoft.amljmes.fortysix.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.anolesoft.amljmes.fortysix.dto.*;
import com.anolesoft.amljmes.fortysix.listener.PtjhListener;
import com.anolesoft.amljmes.fortysix.service.info.MesBzzPtjhInfoService;
import com.anolesoft.amljmes.fortysix.service.mapper.AddPtdMapper;
import com.anolesoft.common.core.constant.HttpStatus;
import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.common.security.util.SecurityUtils;
import com.anolesoft.yr.demo.BaseQueryParamVO;
import com.anolesoft.yr.demo.PageResult;
import com.anolesoft.yr.util.Constants;
import lombok.*;
import lombok.experimental.SuperBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author lx
 * @date 2022/11/21
 * 配套计划
 */
@RestController
@CrossOrigin
@RequestMapping("/ptjh")
@Slf4j
public class MesBzzPtjhInfoController {
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @SuperBuilder
    @ToString(callSuper = true)
    @EqualsAndHashCode(callSuper=true)
    public static class DemoVO extends BaseQueryParamVO implements Serializable {
        private String fathernumber;// 父件号
        private String fathername;// 父件名称
        private String dispatchnoofgeneral;//部总装派工号
        private String model;//机型
        private String batch;//批次
        private String sorties;//架次
        private String factorycode;//厂代号
        private String proportion;//比例
        private Integer generatematchingDocument;//是否生成配套单 默认0:未生成 1:已生成
    }

    @Autowired
    public MesBzzPtjhInfoService mesBzzPtjhInfoService;

    @Autowired
    AddPtdMapper addPtdMapper;

    //查询
    @PostMapping(value="/query",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public AjaxResult queryMesBzzPtjhInfo(DemoVO demoVO){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        demoVO.setFactorycode(loginUser.getFacCode());

        List<NewPtjhDto> allList = mesBzzPtjhInfoService.queryMesBzzPtjhInfo(demoVO);
        int pn =  demoVO.getPageNo().intValue();
        int ps = demoVO.getPageSize().intValue();
        int endIndex = pn * ps > allList.size() ? allList.size() : pn*ps;
        List<NewPtjhDto> list = allList.subList( (pn-1) *ps, endIndex  );
        PageResult pageResult = new PageResult(list, demoVO.getPageSize(), demoVO.getPageNo(), allList.size());
        return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_SUCCESS_MESSAGE,pageResult);
    }

    //修改
    @PostMapping(value="/update", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public AjaxResult updateMesWpgProcess(@RequestBody NewPtjhDto inFoDtoParam){
        System.out.println(">>>>>>update");
        System.out.println(">>>>>>inFoDtoParam"+inFoDtoParam);
        return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_SUCCESS_MESSAGE,mesBzzPtjhInfoService.updatePtjh(inFoDtoParam));
    }

    // 批量删除
    @PostMapping(value="/delete", produces = MediaType.APPLICATION_JSON_VALUE)
    public AjaxResult delete(@RequestBody String[] objuids){
        System.out.println(">>>>>>delete");
        List<String> asList = null;
        if (objuids != null) {
            asList = Arrays.asList(objuids);
        }
        return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_SUCCESS_MESSAGE,mesBzzPtjhInfoService.delete(asList));
    }

    // 导入
    @PostMapping(value="/import")
    public AjaxResult importEqual(MultipartFile file){
        log.debug("文件名：{}", file.getOriginalFilename());
        log.debug("文件大小：{}", file.getSize());

        String message = "";
        try {
            EasyExcel.read(file.getInputStream(), PtjhImport.class, new PtjhListener(mesBzzPtjhInfoService)).sheet(0).doRead();
            message = "文件导入成功！";
        } catch (IOException e) {
            log.error("导入失败：{}", e.getMessage());
            e.printStackTrace();
            message = "文件导入异常" + e.getMessage();
        } catch (Exception e1) {
            log.error("导入失败：{}", e1.getMessage());
            e1.printStackTrace();
            message = e1.getMessage();
        } finally {
            return AjaxResult.success(message);
        }
    }

    // 导出
    @PostMapping(value="/export")
    public void queryMatchExport(@RequestBody DemoVO demoVO, HttpServletResponse response){
        long start = System.currentTimeMillis();
        //OutputStream output = null;
        LoginUser loginUser = com.anolesoft.yr.util.SecurityUtils.getLoginUser();
        demoVO.setFactorycode(loginUser.getFacCode());
        log.debug("demoVO: {}", demoVO);
        try {
            OutputStream output = response.getOutputStream();
            //字符集
            response.setCharacterEncoding("utf-8");
            //类型
            response.setContentType("multipart/form-data");
            //响应头
            response.setHeader("Content-Disposition", "attachment;filename="+new String(("export.xlsx").getBytes("gb2312"),"ISO8859-1"));
            //总条数
            List<PtjhExport> data = mesBzzPtjhInfoService.exportPtjh(demoVO);
            int total = data.size();
            log.debug("total:" + total);
            //单个sheet最大条数
            int size = 100000;
            //sheet数
            int sheet = total / size + 1;
            //单次查询条数
            int pageSize = 1000;
            ExcelWriter excelWriter = EasyExcel.write(output).build();
            //执行查询次数
            int count = 1;
            for (int i = 0; i < sheet ; i++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i,"进度核对" + (i+1))
                        .head(PtjhExport.class)
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .build();
                int rolling;
                if (i == sheet - 1) {
                    rolling = (total - i * size) / pageSize + 1;
                } else {
                    rolling = size / pageSize;
                }
                int startRow = i * size;
                for (int j = 0; j < rolling; j++) {
                    startRow = startRow + j * pageSize;
                    int endIndex = startRow + pageSize > data.size() ? data.size() : startRow + pageSize;
                    List<PtjhExport> list = data.subList( startRow, endIndex  );
                    excelWriter.write(list, writeSheet);
                    count++;
                }
            }
            log.debug("查询次数：" + (count - 1) + "次");
            //刷新流
            excelWriter.finish();
            output.flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            log.error("导出失败：{}", e.getMessage());
            e.printStackTrace();
        } finally {
            long end = System.currentTimeMillis();
            log.debug("总用时：" + (end - start) + "毫秒");
        }
    }

    // 生成配套单
    @Transactional
    @PostMapping(value="/add",produces= MediaType.APPLICATION_JSON_VALUE)
    public AjaxResult queryScptdAll(@RequestBody DemoVO demoVO) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        demoVO.setFactorycode(loginUser.getFacCode());
        List<NewPtjhDto> dto = mesBzzPtjhInfoService.queryMesBzzPtjhInfo2(demoVO);
        if (dto.size() == 0) {
            AjaxResult success = AjaxResult.success();
            success.put("data", "没有可生成配套单数据");
            return success;
        }
        int a = 0;

        //添加数据
        MesBzzPtdDto mesBzzPtdDto = new MesBzzPtdDto();
        String objuidPtd = IdUtil.simpleUUID();
        mesBzzPtdDto.setObjuid(objuidPtd);//主键
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
        Date date = new Date(System.currentTimeMillis());
        String random = ""+Math.random();
        String substring = random.substring(random.length()-4);
        mesBzzPtdDto.setOrderNumber("DDBH"+formatter.format(date)+substring);//订单编号
        mesBzzPtdDto.setBatch(dto.get(0).getBatch());//批次
        mesBzzPtdDto.setModel(dto.get(0).getModel());//机型
        mesBzzPtdDto.setSorties(dto.get(0).getSorties());//架次
        mesBzzPtdDto.setDispatch(dto.get(0).getDispatchnoofgeneral());//部总装派工号
        mesBzzPtdDto.setFactoryCode(dto.get(0).getFactorycode());//厂代号
        mesBzzPtdDto.setFounder(loginUser.getEmpUid());//创建人
        mesBzzPtdDto.setFathernumber(dto.get(0).getFathernumber());//父件号
        mesBzzPtdDto.setFathername(dto.get(0).getFathername());//父件名称
        mesBzzPtdDto.setProportion(dto.get(0).getProportion());//比例
        mesBzzPtdDto.setAffiliation(dto.get(0).getAffiliation());// 所属专业
        int b=addPtdMapper.addPtd(mesBzzPtdDto);


        for(int i = 0;i<dto.size();i++){
            NewPtjhDto list = dto.get(i);

            PtmlVo ptmlVo = new PtmlVo();
            ptmlVo.setChangdaihao(list.getFactorycode());
            ptmlVo.setJixing(list.getModel());
            ptmlVo.setTuhao(list.getDrawingno());
            ptmlVo.setJiaofuchejian(list.getDeliveryworkshop());//交付车间
            ptmlVo.setJieshouchejian(list.getReceivingworkshop());//接收车间
            ptmlVo.setJiaofushunxu(list.getDeliverysequence());//交付顺序
            ptmlVo.setFathernumber(list.getFathernumber());//父件号
            PtmlVo allList = addPtdMapper.queryPtmlInfo(ptmlVo);
            System.out.print(allList+",,,,,,,,,,,,,,,,,,,,");



            //明细添加数据
            MesBzzPtdmxDto mesBzzPtdmxDto = new MesBzzPtdmxDto();
            mesBzzPtdmxDto.setItemNo(list.getItemno());//物料号
            mesBzzPtdmxDto.setPartDrawingNo(list.getDrawingno());//图号
            mesBzzPtdmxDto.setMaterialType(list.getMaterialtype());//物料类型
            mesBzzPtdmxDto.setDemandTime(list.getDemandtime());//需求时间
            mesBzzPtdmxDto.setDemandQuantity(list.getDemandquantity());//需求数量
            mesBzzPtdmxDto.setQuantityOfMissingParts(list.getDemandquantity());//缺件数量
            mesBzzPtdmxDto.setMatchingDocPk(objuidPtd);//配套单主键
            mesBzzPtdmxDto.setFactoryCode(list.getFactorycode());//厂代号
            mesBzzPtdmxDto.setPaigonghao(list.getDispatchnoofgeneral());//派工号
            mesBzzPtdmxDto.setJixing(list.getModel());//机型
            mesBzzPtdmxDto.setJiaofuchejian(list.getDeliveryworkshop());//交付车间
            mesBzzPtdmxDto.setJieshouchejian(list.getReceivingworkshop());//接收车间
            mesBzzPtdmxDto.setJiaofushunxu(list.getDeliverysequence());//交付顺序
            mesBzzPtdmxDto.setSerialnumber(list.getSerialnumber());//顺序号
            mesBzzPtdmxDto.setName(list.getName());//名称
            mesBzzPtdmxDto.setDivisionroute(list.getDivisionroute());//分工线路
            mesBzzPtdmxDto.setScheduledstarttime(list.getScheduledstarttime());//计划开工时间
            mesBzzPtdmxDto.setScheduledendtime(list.getScheduledendtime());//计划完工时间
            mesBzzPtdmxDto.setProportion(list.getProportion());//比例
            mesBzzPtdmxDto.setAffiliation(list.getAffiliation());// 所属专业
            mesBzzPtdmxDto.setMonumber(list.getMonumber());// mo编号
            if(allList==null){
                mesBzzPtdmxDto.setDanwei("");// 单位
                mesBzzPtdmxDto.setDanjishu("");// 单机数
                mesBzzPtdmxDto.setSupplier("");// 承制单位
            }else {
                mesBzzPtdmxDto.setDanwei(allList.getDanwei());// 单位
                mesBzzPtdmxDto.setDanjishu(allList.getDanjishu());// 单机数
                mesBzzPtdmxDto.setSupplier(allList.getChengzhidanwei());// 承制单位
            }

            // 调sql
            int c=addPtdMapper.addPtdmx(mesBzzPtdmxDto);
            int d=addPtdMapper.update(list.getObjuid());
            if(c > 0 && d > 0){
                a++;
            }
        }

        if(b > 0 && a == dto.size()){
            AjaxResult success = AjaxResult.success();
            success.put("data", "成功");
            return success;
        } else {
            AjaxResult success = AjaxResult.success();
            success.put("data", "失败");
            return success;
        }
    }
}
